'''
1 要加密的数据
user id
2 要加密的算法 
pip install pyjwt
3 加密的秘钥
secret_key

'''
from functools import wraps
import jwt
from flask import current_app,request
import time



#生成token
def generate_token(data):
    #增加失效时间
    # data.update({'exp':time.time() + 3})
    data.update({'exp':time.time() + current_app.config['JWT_EXPIRATION_DELTA']})
    #数据加密
    token = jwt.encode(data,current_app.config['SECRET_KEY'],algorithm='HS256')
    return token

#解密token
def verify_token(token):
    #数据的解密
    try:
        data = jwt.decode(token,current_app.config['SECRET_KEY'],algorithms=['HS256'])
    except Exception as e:
        return None
    return data

#验证登录有效性
def login_required(view_func):
    @wraps(view_func)
    def verify_valid(*args,**kwargs):
        token = request.headers.get('token')
        #验证
        if verify_token(token):
            return view_func(*args,**kwargs)
        else:
            return {'status':401,'msg':'token无效'}
    return verify_valid